package leetcode.code1926;

import java.util.LinkedList;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;


//执行用时：7 ms, 在所有 Java 提交中击败了30.38%的用户
//
//内存消耗：42.9 MB, 在所有 Java 提交中击败了24.53%的用户
//
//通过测试用例：194 / 194
public class Solution implements IDebug {

	public int nearestExit(char[][] maze, int[] entrance) {
		int[] d = new int[] { 0, -1, 0, 1, -1, 0, 1, 0 };
		int m = maze.length, n = maze[0].length;
		int x = entrance[0], y = entrance[1];
		Queue<int[]> queue = new LinkedList<>();
		boolean[][] been = new boolean[m][n];
		been[x][y] = true;
		queue.add(new int[] { x, y, 0 });
		while (!queue.isEmpty()) {
			int[] cur = queue.poll();
			x = cur[0];
			y = cur[1];
			int dist = cur[2] + 1;
			for (int i = 0; i < 8; i += 2) {
				int nextx = x + d[i], nexty = y + d[i + 1];
				if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && !been[nextx][nexty]
						&& maze[nextx][nexty] == '.') {
					if (nextx == 0 || nextx == m - 1 || nexty == 0 || nexty == n - 1) {
						return dist;
					}
					been[nextx][nexty] = true;
					queue.add(new int[] { nextx, nexty, dist });
				}
			}
		}
		return -1;
	}

	@Override
	public void debug4() {
		H.compare(1,
				this.nearestExit(
						H.str2array5("[[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]]"),
						H.str2array3("[1,2]")));
		H.compare(2,
				this.nearestExit(
						H.str2array5("[[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]]"),
						H.str2array3("[1,0]")));
		H.compare(-1,
				this.nearestExit(
						H.str2array5("[[\".\",\"+\"]]"),
						H.str2array3("[0,0]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
